package org.jprobe.utils;

import java.lang.reflect.Array;
/**
* Convenience method for producing a simple textual
* representation of an array.
*
* <P>The format of the returned <code>String</code> is the same as
* <code>AbstractCollection.toString</code>:
* <ul>
* <li>non-empty array: [blah, blah]
* <li>empty array: []
* <li>null array: null
* </ul>
*
* @author Jerome Lacoste
* @author www.javapractices.com
*/
public class arrays {
	 /**
	  * <code>aArray</code> is a possibly-null array whose elements are
	  * primitives or objects; arrays of arrays are also valid, in which case
	  * <code>aArray</code> is rendered in a nested, recursive fashion.
	  */
	public static String toString(Object aArray){
		if ( aArray == null ) return fNULL;
		checkObjectIsArray(aArray);

		StringBuilder result = new StringBuilder( fSTART_CHAR );
		int length = Array.getLength(aArray);
		for ( int idx = 0 ; idx < length ; ++idx ) {
			Object item = Array.get(aArray, idx);
			if ( isNonNullArray(item) ){
				//recursive call!
				result.append( toString(item) );
			}
			else{
				result.append( item );
			}
			if ( ! isLastItem(idx, length) ) {
				result.append(fSEPARATOR);
			}
		}
		result.append(fEND_CHAR);
		return result.toString();
	}

	// PRIVATE //
	private static final String fSTART_CHAR = "[";
	private static final String fEND_CHAR = "]";
	private static final String fSEPARATOR = ", ";
	private static final String fNULL = "null";

	private static void checkObjectIsArray(Object aArray){
		if ( ! aArray.getClass().isArray() ) {
			throw new IllegalArgumentException("Object is not an array.");
		}
	}

	private static boolean isNonNullArray(Object aItem){
		return aItem != null && aItem.getClass().isArray();
	}

	private static boolean isLastItem(int aIdx, int aLength){
		return (aIdx == aLength - 1);
	}

}
